// 游戏配置
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 动态设置画布大小以适配设备
function resizeCanvas() {
    const container = document.getElementById('gameCanvas');
    const containerWidth = container.clientWidth;
    const containerHeight = window.innerHeight - 200; // 减去头部和底部的空间
    
    // 设置画布宽高比为 3:4（适合竖屏）
    const aspectRatio = 3 / 4;
    
    if (containerWidth * (1 / aspectRatio) <= containerHeight) {
        canvas.width = Math.min(600, containerWidth);
        canvas.height = canvas.width / aspectRatio;
    } else {
        canvas.height = Math.min(800, containerHeight);
        canvas.width = canvas.height * aspectRatio;
    }
    
    // 移动端优化
    if (window.innerWidth <= 768) {
        canvas.width = Math.min(450, containerWidth - 10);
        canvas.height = canvas.width / aspectRatio;
    }
}

// 初始化画布大小
resizeCanvas();

// 监听窗口大小变化
let resizeTimeout;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
        resizeCanvas();
        if (player) {
            // 确保玩家位置在有效范围内
            player.x = Math.max(0, Math.min(canvas.width - player.width, player.x));
        }
    }, 250);
});

// 游戏状态
let gameState = 'start'; // start, playing, gameOver
let score = 0;
let lives = 3;
let level = 1;
let stage = 1; // 关卡
let highScore = localStorage.getItem('highScore') || 0;

// 得分系统
let combo = 0; // 连击数
let maxCombo = 0; // 最大连击
let lastKillTime = 0; // 上次击杀时间
let comboTimeout = 2000; // 连击超时（毫秒）
let totalKills = 0; // 总击杀数

// 游戏对象
let player;
let bullets = [];
let enemies = [];
let explosions = [];
let particles = [];
let powerups = []; // 道具
let boss = null; // Boss

// 控制
let keys = {};
let mouseX = canvas.width / 2;
let autoShoot = false;

// 游戏循环
let animationId;
let lastEnemySpawn = 0;
let enemySpawnRate = 1000; // 毫秒
let bossStage = false; // 是否为Boss关卡
let bossTransition = false; // Boss切换中

// 关卡配置
const STAGE_CONFIG = {
    1: { name: '新手上路', enemySpawnRate: 1200, enemySpeed: 1.2, bossAt: 500 },
    2: { name: '渐入佳境', enemySpawnRate: 1000, enemySpeed: 1.5, bossAt: 1000 },
    3: { name: '高手之路', enemySpawnRate: 800, enemySpeed: 1.8, bossAt: 1500 },
    4: { name: '极限挑战', enemySpawnRate: 600, enemySpeed: 2.2, bossAt: 2000 },
    5: { name: '王者归来', enemySpawnRate: 400, enemySpeed: 2.5, bossAt: 2500 }
};

// 玩家飞机类
class Player {
    constructor() {
        // 根据屏幕尺寸调整飞机大小
        const isMobile = window.innerWidth <= 768;
        this.width = isMobile ? 40 : 50;
        this.height = isMobile ? 40 : 50;
        this.x = canvas.width / 2 - this.width / 2;
        this.y = canvas.height - 100;
        this.speed = isMobile ? 8 : 7; // 移动端速度稍快
        this.shootCooldown = 0;
        this.shootRate = isMobile ? 8 : 10; // 移动端射击更快
        
        // 血量和护盾系统
        this.maxHealth = 100;
        this.health = 100;
        this.maxShield = 50;
        this.shield = 0;
        this.invincible = false; // 无敌状态
        this.invincibleTime = 0;
        
        // 武器等级
        this.weaponLevel = 1; // 1-3级
    }

    draw() {
        // 无敌闪烁效果
        if (this.invincible && Math.floor(Date.now() / 100) % 2 === 0) {
            ctx.globalAlpha = 0.5;
        }
        
        // 护盾效果
        if (this.shield > 0) {
            ctx.strokeStyle = `rgba(0, 200, 255, ${0.3 + this.shield / this.maxShield * 0.5})`;
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.arc(this.x + this.width / 2, this.y + this.height / 2, this.width * 0.8, 0, Math.PI * 2);
            ctx.stroke();
        }
        
        // 绘制飞机身体
        ctx.fillStyle = '#4a90e2';
        ctx.beginPath();
        ctx.moveTo(this.x + this.width / 2, this.y);
        ctx.lineTo(this.x + this.width, this.y + this.height);
        ctx.lineTo(this.x + this.width / 2, this.y + this.height * 0.8);
        ctx.lineTo(this.x, this.y + this.height);
        ctx.closePath();
        ctx.fill();

        // 绘制飞机翅膀
        ctx.fillStyle = '#357abd';
        ctx.fillRect(this.x, this.y + this.height * 0.5, this.width * 0.3, this.height * 0.3);
        ctx.fillRect(this.x + this.width * 0.7, this.y + this.height * 0.5, this.width * 0.3, this.height * 0.3);

        // 绘制驾驶舱
        ctx.fillStyle = '#ffd700';
        ctx.beginPath();
        ctx.arc(this.x + this.width / 2, this.y + this.height * 0.4, this.width * 0.15, 0, Math.PI * 2);
        ctx.fill();

        // 引擎火焰效果
        if (Math.random() > 0.5) {
            ctx.fillStyle = `rgba(255, ${150 + Math.random() * 100}, 0, 0.8)`;
            ctx.beginPath();
            ctx.arc(this.x + this.width / 2, this.y + this.height, 8, 0, Math.PI * 2);
            ctx.fill();
        }
        
        ctx.globalAlpha = 1;
        
        // 绘制血条
        this.drawHealthBar();
    }
    
    drawHealthBar() {
        const barWidth = this.width;
        const barHeight = 4;
        const barX = this.x;
        const barY = this.y - 12;
        
        // 血条背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 血量
        const healthPercent = this.health / this.maxHealth;
        const healthColor = healthPercent > 0.6 ? '#00ff00' : healthPercent > 0.3 ? '#ffaa00' : '#ff0000';
        ctx.fillStyle = healthColor;
        ctx.fillRect(barX, barY, barWidth * healthPercent, barHeight);
        
        // 护盾条
        if (this.shield > 0) {
            const shieldPercent = this.shield / this.maxShield;
            ctx.fillStyle = '#00ccff';
            ctx.fillRect(barX, barY - 6, barWidth * shieldPercent, 3);
        }
    }

    update() {
        // 键盘控制
        if (keys['ArrowLeft'] && this.x > 0) {
            this.x -= this.speed;
        }
        if (keys['ArrowRight'] && this.x < canvas.width - this.width) {
            this.x += this.speed;
        }

        // 鼠标控制（仅在非触摸模式下使用平滑移动）
        if (mouseX !== null && lastTouchX === null) {
            const rect = canvas.getBoundingClientRect();
            const scaleX = canvas.width / rect.width;
            let targetX = (mouseX * scaleX) - this.width / 2;
            targetX = Math.max(0, Math.min(canvas.width - this.width, targetX));
            this.x += (targetX - this.x) * 0.2;
        }

        // 射击冷却
        if (this.shootCooldown > 0) {
            this.shootCooldown--;
        }

        // 自动射击
        if (autoShoot && this.shootCooldown === 0) {
            this.shoot();
        }
        
        // 无敌时间
        if (this.invincible && this.invincibleTime > 0) {
            this.invincibleTime--;
            if (this.invincibleTime <= 0) {
                this.invincible = false;
            }
        }
    }

    shoot() {
        if (this.shootCooldown === 0) {
            // 根据武器等级发射不同数量的子弹
            if (this.weaponLevel === 1) {
                bullets.push(new Bullet(this.x + this.width / 2 - 3, this.y));
            } else if (this.weaponLevel === 2) {
                bullets.push(new Bullet(this.x + this.width / 2 - 10, this.y));
                bullets.push(new Bullet(this.x + this.width / 2 + 4, this.y));
            } else if (this.weaponLevel === 3) {
                bullets.push(new Bullet(this.x + this.width / 2 - 3, this.y));
                bullets.push(new Bullet(this.x + this.width / 2 - 15, this.y + 10));
                bullets.push(new Bullet(this.x + this.width / 2 + 9, this.y + 10));
            }
            this.shootCooldown = this.shootRate;
        }
    }
    
    takeDamage(damage) {
        if (this.invincible) return false;
        
        // 先扣护盾
        if (this.shield > 0) {
            this.shield -= damage;
            if (this.shield < 0) {
                this.health += this.shield; // 剩余伤害扣血
                this.shield = 0;
            }
        } else {
            this.health -= damage;
        }
        
        // 受伤后短暂无敌
        this.invincible = true;
        this.invincibleTime = 60; // 1秒无敌
        
        return this.health <= 0;
    }
    
    heal(amount) {
        this.health = Math.min(this.maxHealth, this.health + amount);
    }
    
    addShield(amount) {
        this.shield = Math.min(this.maxShield, this.shield + amount);
    }
    
    upgradeWeapon() {
        if (this.weaponLevel < 3) {
            this.weaponLevel++;
        }
    }
}

// 子弹类
class Bullet {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 6;
        this.height = 20;
        this.speed = 12;
        this.color = '#ffff00';
    }

    draw() {
        ctx.fillStyle = this.color;
        ctx.shadowBlur = 10;
        ctx.shadowColor = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.shadowBlur = 0;
    }

    update() {
        this.y -= this.speed;
    }

    isOffScreen() {
        return this.y < -this.height;
    }
}

// 敌机类
class Enemy {
    constructor() {
        // 根据屏幕尺寸调整敌机大小
        const isMobile = window.innerWidth <= 768;
        const baseSize = isMobile ? 30 : 40;
        const sizeVariation = isMobile ? 15 : 20;
        
        this.width = baseSize + Math.random() * sizeVariation;
        this.height = baseSize + Math.random() * sizeVariation;
        this.x = Math.random() * (canvas.width - this.width);
        this.y = -this.height;
        this.speed = 2 + Math.random() * 2 + level * 0.3;
        this.health = Math.floor(Math.random() * 3) + 1;
        this.maxHealth = this.health;
        this.points = this.health * 10;
        
        // 不同颜色代表不同类型
        const colors = ['#ff4757', '#ff6348', '#ff7f50'];
        this.color = colors[this.health - 1];
    }

    draw() {
        // 绘制敌机
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.moveTo(this.x + this.width / 2, this.y + this.height);
        ctx.lineTo(this.x + this.width, this.y);
        ctx.lineTo(this.x + this.width / 2, this.y + this.height * 0.3);
        ctx.lineTo(this.x, this.y);
        ctx.closePath();
        ctx.fill();

        // 血条
        if (this.health < this.maxHealth) {
            ctx.fillStyle = '#ff0000';
            ctx.fillRect(this.x, this.y - 10, this.width, 4);
            ctx.fillStyle = '#00ff00';
            ctx.fillRect(this.x, this.y - 10, this.width * (this.health / this.maxHealth), 4);
        }
    }

    update() {
        this.y += this.speed;
    }

    isOffScreen() {
        return this.y > canvas.height;
    }

    hit() {
        this.health--;
        return this.health <= 0;
    }
}

// 爆炸效果类
class Explosion {
    constructor(x, y, size = 30) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.maxSize = size * 2;
        this.alpha = 1;
        this.growing = true;
    }

    draw() {
        ctx.save();
        ctx.globalAlpha = this.alpha;
        
        // 外圈
        const gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
        gradient.addColorStop(0, '#ffffff');
        gradient.addColorStop(0.3, '#ffff00');
        gradient.addColorStop(0.6, '#ff6600');
        gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.restore();
    }

    update() {
        if (this.growing) {
            this.size += 2;
            if (this.size >= this.maxSize) {
                this.growing = false;
            }
        } else {
            this.alpha -= 0.05;
        }
    }

    isFinished() {
        return this.alpha <= 0;
    }
}

// 粒子效果类
class Particle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.vx = (Math.random() - 0.5) * 6;
        this.vy = (Math.random() - 0.5) * 6;
        this.size = Math.random() * 3 + 1;
        this.life = 1;
        this.color = `hsl(${Math.random() * 60 + 10}, 100%, 50%)`;
    }

    draw() {
        ctx.save();
        ctx.globalAlpha = this.life;
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
    }

    update() {
        this.x += this.vx;
        this.y += this.vy;
        this.life -= 0.02;
        this.size *= 0.95;
    }

    isFinished() {
        return this.life <= 0;
    }
}

// 道具类
class Powerup {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.width = 30;
        this.height = 30;
        this.speed = 2;
        this.type = type; // 'health', 'shield', 'weapon'
        this.rotation = 0;
        
        // 不同道具的配置
        this.config = {
            health: { color: '#ff0000', symbol: '❤️', name: '生命' },
            shield: { color: '#00ccff', symbol: '🛡️', name: '护盾' },
            weapon: { color: '#ffaa00', symbol: '⚡', name: '武器' }
        };
    }
    
    draw() {
        ctx.save();
        ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
        ctx.rotate(this.rotation);
        
        // 绘制光环
        ctx.strokeStyle = this.config[this.type].color;
        ctx.lineWidth = 2;
        ctx.shadowBlur = 10;
        ctx.shadowColor = this.config[this.type].color;
        ctx.strokeRect(-this.width / 2, -this.height / 2, this.width, this.height);
        
        // 绘制符号
        ctx.font = '20px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(this.config[this.type].symbol, 0, 0);
        
        ctx.restore();
    }
    
    update() {
        this.y += this.speed;
        this.rotation += 0.05;
    }
    
    isOffScreen() {
        return this.y > canvas.height;
    }
}

// Boss类
class Boss {
    constructor() {
        this.width = 100;
        this.height = 80;
        this.x = canvas.width / 2 - this.width / 2;
        this.y = -this.height;
        this.speed = 1;
        this.maxHealth = 200 + stage * 100;
        this.health = this.maxHealth;
        this.direction = 1;
        this.shootCooldown = 0;
        this.shootRate = 60;
        this.movePattern = 0;
        this.phase = 1; // Boss阶段
        
        // Boss进入动画
        this.entering = true;
        this.targetY = 50;
    }
    
    draw() {
        // Boss身体
        ctx.fillStyle = '#ff0000';
        ctx.shadowBlur = 20;
        ctx.shadowColor = '#ff0000';
        
        ctx.beginPath();
        ctx.moveTo(this.x + this.width / 2, this.y);
        ctx.lineTo(this.x + this.width, this.y + this.height * 0.3);
        ctx.lineTo(this.x + this.width * 0.8, this.y + this.height);
        ctx.lineTo(this.x + this.width * 0.2, this.y + this.height);
        ctx.lineTo(this.x, this.y + this.height * 0.3);
        ctx.closePath();
        ctx.fill();
        
        // Boss眼睛
        ctx.fillStyle = '#ffff00';
        ctx.beginPath();
        ctx.arc(this.x + this.width * 0.35, this.y + this.height * 0.4, 8, 0, Math.PI * 2);
        ctx.arc(this.x + this.width * 0.65, this.y + this.height * 0.4, 8, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.shadowBlur = 0;
        
        // Boss血条
        this.drawHealthBar();
    }
    
    drawHealthBar() {
        const barWidth = this.width;
        const barHeight = 8;
        const barX = this.x;
        const barY = this.y - 20;
        
        // 血条背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 血量
        const healthPercent = this.health / this.maxHealth;
        const gradient = ctx.createLinearGradient(barX, 0, barX + barWidth, 0);
        if (healthPercent > 0.5) {
            gradient.addColorStop(0, '#ff0000');
            gradient.addColorStop(1, '#ff6600');
        } else {
            gradient.addColorStop(0, '#ff0000');
            gradient.addColorStop(1, '#ffff00');
        }
        ctx.fillStyle = gradient;
        ctx.fillRect(barX, barY, barWidth * healthPercent, barHeight);
        
        // Boss名称
        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`BOSS - ${this.health}/${this.maxHealth}`, this.x + this.width / 2, barY - 8);
    }
    
    update() {
        // 进入动画
        if (this.entering) {
            this.y += 3; // 加快进入速度
            if (this.y >= this.targetY) {
                this.entering = false;
                this.y = this.targetY; // 确保准确到达目标位置
            }
            return;
        }
        
        // 移动模式
        this.x += this.direction * this.speed * 2;
        if (this.x <= 0 || this.x >= canvas.width - this.width) {
            this.direction *= -1;
        }
        
        // 根据血量改变阶段
        if (this.health < this.maxHealth * 0.5 && this.phase === 1) {
            this.phase = 2;
            this.speed = 1.5;
            this.shootRate = 40;
        }
        
        // Boss射击
        if (this.shootCooldown > 0) {
            this.shootCooldown--;
        } else {
            this.bossShoot();
            this.shootCooldown = this.shootRate;
        }
    }
    
    bossShoot() {
        // Boss发射多个子弹
        const bulletCount = this.phase === 1 ? 3 : 5;
        for (let i = 0; i < bulletCount; i++) {
            enemies.push(new EnemyBullet(
                this.x + (this.width / (bulletCount + 1)) * (i + 1),
                this.y + this.height
            ));
        }
    }
    
    hit(damage = 10) {
        this.health -= damage;
        return this.health <= 0;
    }
}

// 敌机子弹类
class EnemyBullet {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 8;
        this.height = 15;
        this.speed = 4;
        this.color = '#ff0000';
    }
    
    draw() {
        ctx.fillStyle = this.color;
        ctx.shadowBlur = 10;
        ctx.shadowColor = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.shadowBlur = 0;
    }
    
    update() {
        this.y += this.speed;
    }
    
    isOffScreen() {
        return this.y > canvas.height;
    }
}

// 碰撞检测
function checkCollision(obj1, obj2) {
    return obj1.x < obj2.x + obj2.width &&
           obj1.x + obj1.width > obj2.x &&
           obj1.y < obj2.y + obj2.height &&
           obj1.y + obj1.height > obj2.y;
}

// 创建爆炸效果
function createExplosion(x, y, particleCount = 20) {
    explosions.push(new Explosion(x, y));
    for (let i = 0; i < particleCount; i++) {
        particles.push(new Particle(x, y));
    }
}

// 显示得分提示
function showScorePopup(x, y, points, text = '') {
    const popup = {
        x: x,
        y: y,
        text: text || `+${points}`,
        alpha: 1,
        vy: -2
    };
    
    const drawPopup = () => {
        if (popup.alpha <= 0) return false;
        
        ctx.save();
        ctx.globalAlpha = popup.alpha;
        ctx.fillStyle = combo > 5 ? '#ffff00' : '#ffffff';
        ctx.font = 'bold 20px Arial';
        ctx.textAlign = 'center';
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 3;
        ctx.strokeText(popup.text, popup.x, popup.y);
        ctx.fillText(popup.text, popup.x, popup.y);
        ctx.restore();
        
        popup.y += popup.vy;
        popup.alpha -= 0.02;
        return true;
    };
    
    const animate = () => {
        if (drawPopup()) {
            requestAnimationFrame(animate);
        }
    };
    animate();
}

// 更新连击
function updateCombo() {
    const now = Date.now();
    if (now - lastKillTime > comboTimeout) {
        combo = 0;
    }
}

// 增加得分
function addScore(points, x, y) {
    // 连击奖励
    const comboBonus = Math.floor(points * combo * 0.1);
    const totalPoints = points + comboBonus;
    
    score += totalPoints;
    
    // 显示得分提示
    if (combo > 1) {
        showScorePopup(x, y, totalPoints, `+${totalPoints} (${combo}x)`);
    } else {
        showScorePopup(x, y, totalPoints);
    }
    
    updateUI();
}

// 随机掉落道具
function dropPowerup(x, y) {
    // 10%概率掉落道具
    if (Math.random() < 0.1) {
        const types = ['health', 'shield', 'weapon'];
        const type = types[Math.floor(Math.random() * types.length)];
        powerups.push(new Powerup(x, y, type));
    }
}

// 更新分数显示
function updateUI() {
    document.getElementById('score').textContent = score;
    document.getElementById('lives').textContent = '❤️'.repeat(Math.max(0, lives));
    document.getElementById('level').textContent = level;
}

// 检查是否触发Boss（仅用于第一关）
function checkBossSpawn() {
    // 只在第一关且未触发过Boss时检查
    if (stage !== 1) return;
    if (stage > 5) return;
    
    const config = STAGE_CONFIG[stage];
    if (!config) return;
    
    if (!bossStage && !boss && score >= config.bossAt) {
        bossStage = true;
        boss = new Boss();
        enemies = []; // 清空普通敌机
        powerups = []; // 清空道具，避免干扰
        showMessage(`⚠️ 关卡${stage} BOSS出现！⚠️`);
    }
}

// 显示消息
function showMessage(text) {
    const msgDiv = document.createElement('div');
    msgDiv.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(255, 0, 0, 0.9);
        color: white;
        padding: 20px 40px;
        font-size: 24px;
        font-weight: bold;
        border-radius: 10px;
        z-index: 1000;
        animation: fadeIn 0.3s;
    `;
    msgDiv.textContent = text;
    document.body.appendChild(msgDiv);
    
    setTimeout(() => {
        msgDiv.style.animation = 'fadeOut 0.3s';
        setTimeout(() => msgDiv.remove(), 300);
    }, 2000);
}

// 游戏初始化
function initGame() {
    score = 0;
    lives = 3;
    level = 1;
    stage = 1;
    combo = 0;
    maxCombo = 0;
    totalKills = 0;
    bullets = [];
    enemies = [];
    explosions = [];
    particles = [];
    powerups = [];
    boss = null;
    bossStage = false;
    bossTransition = false;
    player = new Player();
    lastEnemySpawn = Date.now();
    lastKillTime = Date.now();
    
    // 根据关卡设置
    const config = STAGE_CONFIG[stage];
    enemySpawnRate = config.enemySpawnRate;
    
    updateUI();
}

// 游戏循环
function gameLoop(timestamp) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制星空背景
    drawStars();

    if (gameState === 'playing') {
        // 更新连击系统
        updateCombo();
        
        // 检查Boss生成
        checkBossSpawn();
        
        // 更新玩家
        player.update();
        player.draw();

        // 绘制游戏信息
        drawGameInfo();

        // Boss模式
        if (boss) {
            boss.update();
            boss.draw();
            
            // Boss子弹碰撞检测（Boss进入动画完成后才能被击中）
            if (!boss.entering) {
                for (let i = bullets.length - 1; i >= 0; i--) {
                    if (checkCollision(bullets[i], boss)) {
                        bullets.splice(i, 1);
                        if (boss.hit(10)) {
                            // Boss被击败
                            console.log(`Boss被击败！当前stage: ${stage}, 即将进入stage: ${stage + 1}`);
                            createExplosion(boss.x + boss.width / 2, boss.y + boss.height / 2, 50);
                            addScore(500, boss.x + boss.width / 2, boss.y + boss.height / 2);
                            
                            // Boss必掉道具（确保在屏幕可见范围内）
                            const dropY = Math.min(boss.y + boss.height / 2, canvas.height / 2);
                            for (let j = 0; j < 3; j++) {
                                const types = ['health', 'shield', 'weapon'];
                                powerups.push(new Powerup(
                                    boss.x + (j - 1) * 40 + boss.width / 2,
                                    dropY,
                                    types[j]
                                ));
                            }
                            
                            boss = null;
                            bossStage = false;
                            bossTransition = true; // 标记进入切换状态
                            stage++;
                            console.log(`Boss已清空，stage更新为: ${stage}`);
                            
                            // 检查是否通关
                            if (stage > 5) {
                                // 通关！
                                console.log('游戏通关！');
                                bossTransition = false;
                                showMessage('🎊 恭喜通关！你是王牌飞行员！🎊');
                                setTimeout(() => {
                                    console.log('显示通关画面');
                                    gameWin();
                                }, 2000);
                            } else {
                                // 进入下一关
                                console.log(`准备进入关卡 ${stage}，3秒后出现Boss`);
                                showMessage(`🎉 进入关卡 ${stage}！🎉`);
                                
                                // 更新关卡配置
                                const config = STAGE_CONFIG[stage];
                                if (config) {
                                    enemySpawnRate = config.enemySpawnRate;
                                }
                                
                                // 3秒后立即触发新Boss，给玩家拾取道具的时间
                                setTimeout(() => {
                                    console.log(`检查是否创建新Boss - gameState: ${gameState}, boss: ${boss}, bossTransition: ${bossTransition}`);
                                    if (gameState === 'playing' && !boss && bossTransition) {
                                        console.log(`创建关卡${stage}的Boss`);
                                        bossStage = true;
                                        bossTransition = false;
                                        boss = new Boss();
                                        enemies = [];
                                        // 不清理道具，让玩家有机会拾取上一个Boss掉落的道具
                                        showMessage(`⚠️ 关卡${stage} BOSS出现！⚠️`);
                                    } else {
                                        console.log('无法创建新Boss，条件不满足');
                                    }
                                }, 3000);
                            }
                        }
                        break;
                    }
                }
            }
            
            // Boss与玩家碰撞（Boss进入动画完成后才能碰撞）
            if (!boss.entering && !player.invincible && checkCollision(player, boss)) {
                if (player.takeDamage(30)) {
                    gameOver();
                } else {
                    createExplosion(player.x + player.width / 2, player.y + player.height / 2);
                }
            }
        } else {
            // 普通敌机生成（仅在第一关且非Boss阶段时生成）
            if (stage === 1 && !bossStage && Date.now() - lastEnemySpawn > enemySpawnRate) {
                enemies.push(new Enemy());
                lastEnemySpawn = Date.now();
            }
        }

        // 更新子弹
        bullets = bullets.filter(bullet => {
            bullet.update();
            bullet.draw();
            return !bullet.isOffScreen();
        });

        // 更新敌机（包括敌机子弹）
        enemies = enemies.filter(enemy => {
            enemy.update();
            enemy.draw();

            // 敌机子弹与玩家碰撞
            if (enemy instanceof EnemyBullet) {
                if (!player.invincible && checkCollision(player, enemy)) {
                    if (player.takeDamage(10)) {
                        gameOver();
                    }
                    createExplosion(enemy.x, enemy.y, 10);
                    return false;
                }
                return !enemy.isOffScreen();
            }

            // 玩家子弹与敌机碰撞
            for (let i = bullets.length - 1; i >= 0; i--) {
                if (checkCollision(bullets[i], enemy)) {
                    bullets.splice(i, 1);
                    if (enemy.hit()) {
                        createExplosion(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                        
                        // 击杀计数和连击
                        totalKills++;
                        combo++;
                        lastKillTime = Date.now();
                        maxCombo = Math.max(maxCombo, combo);
                        
                        // 添加得分
                        addScore(enemy.points, enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                        
                        // 道具掉落
                        dropPowerup(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                        
                        // 升级检测
                        let newLevel = Math.floor(score / 1000) + 1;
                        if (newLevel > level) {
                            level = newLevel;
                            updateUI();
                        }
                        
                        return false;
                    }
                    break;
                }
            }

            // 敌机与玩家碰撞
            if (!player.invincible && checkCollision(player, enemy)) {
                createExplosion(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                if (player.takeDamage(20)) {
                    gameOver();
                }
                return false;
            }

            return !enemy.isOffScreen();
        });

        // 更新道具
        powerups = powerups.filter(powerup => {
            powerup.update();
            powerup.draw();
            
            // 道具与玩家碰撞
            if (checkCollision(player, powerup)) {
                // 应用道具效果
                if (powerup.type === 'health') {
                    player.heal(30);
                    showScorePopup(powerup.x, powerup.y, 0, '+30 HP');
                } else if (powerup.type === 'shield') {
                    player.addShield(30);
                    showScorePopup(powerup.x, powerup.y, 0, '护盾+30');
                } else if (powerup.type === 'weapon') {
                    player.upgradeWeapon();
                    showScorePopup(powerup.x, powerup.y, 0, '武器升级！');
                }
                return false;
            }
            
            return !powerup.isOffScreen();
        });

        // 更新爆炸效果
        explosions = explosions.filter(explosion => {
            explosion.update();
            explosion.draw();
            return !explosion.isFinished();
        });

        // 更新粒子
        particles = particles.filter(particle => {
            particle.update();
            particle.draw();
            return !particle.isFinished();
        });
    }

    animationId = requestAnimationFrame(gameLoop);
}

// 绘制游戏信息
function drawGameInfo() {
    ctx.save();
    
    // 左上角信息
    ctx.fillStyle = '#ffffff';
    ctx.font = 'bold 16px Arial';
    ctx.textAlign = 'left';
    ctx.shadowBlur = 3;
    ctx.shadowColor = '#000000';
    
    // 连击显示
    if (combo > 1) {
        ctx.fillStyle = combo > 10 ? '#ffff00' : combo > 5 ? '#ff9900' : '#ffffff';
        ctx.font = 'bold 24px Arial';
        ctx.fillText(`${combo}x COMBO!`, 10, 30);
        ctx.font = 'bold 16px Arial';
    }
    
    // 关卡信息
    ctx.fillStyle = '#ffffff';
    const config = STAGE_CONFIG[Math.min(stage, 5)];
    if (config) {
        const infoY = combo > 1 ? 60 : 30;
        ctx.fillText(`关卡 ${stage}: ${config.name}`, 10, infoY);
        
        // 只在第一关显示Boss触发分数
        if (!bossStage && !boss && stage === 1) {
            ctx.font = '12px Arial';
            ctx.fillStyle = '#ffaa00';
            ctx.fillText(`${config.bossAt}分触发Boss`, 10, infoY + 20);
            ctx.font = 'bold 16px Arial';
            ctx.fillStyle = '#ffffff';
        }
    }
    
    // 玩家状态栏（左下角）
    const barY = canvas.height - 60;
    ctx.fillText(`HP: ${Math.floor(player.health)}/${player.maxHealth}`, 10, barY);
    ctx.fillText(`护盾: ${Math.floor(player.shield)}/${player.maxShield}`, 10, barY + 20);
    ctx.fillText(`武器: Lv.${player.weaponLevel}`, 10, barY + 40);
    
    // 右上角信息
    ctx.textAlign = 'right';
    ctx.fillText(`击杀: ${totalKills}`, canvas.width - 10, 30);
    ctx.fillText(`最大连击: ${maxCombo}`, canvas.width - 10, 50);
    
    // Boss警告
    if (boss) {
        ctx.textAlign = 'center';
        ctx.fillStyle = '#ff0000';
        ctx.font = 'bold 20px Arial';
        ctx.fillText('⚠️ BOSS战！⚠️', canvas.width / 2, canvas.height - 20);
    }
    
    ctx.shadowBlur = 0;
    ctx.restore();
}

// 绘制星空背景
let stars = [];
function initStars() {
    for (let i = 0; i < 100; i++) {
        stars.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height,
            radius: Math.random() * 2,
            speed: Math.random() * 2 + 0.5
        });
    }
}

function drawStars() {
    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
    stars.forEach(star => {
        ctx.beginPath();
        ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
        ctx.fill();
        
        star.y += star.speed;
        if (star.y > canvas.height) {
            star.y = 0;
            star.x = Math.random() * canvas.width;
        }
    });
}

// 游戏结束
function gameOver() {
    gameState = 'gameOver';
    
    // 更新最高分
    if (score > highScore) {
        highScore = score;
        localStorage.setItem('highScore', highScore);
    }
    
    document.getElementById('finalScore').textContent = score;
    document.getElementById('highScore').textContent = highScore;
    document.getElementById('gameOverScreen').classList.remove('hidden');
}

// 游戏通关
function gameWin() {
    gameState = 'gameWin';
    
    // 更新最高分
    if (score > highScore) {
        highScore = score;
        localStorage.setItem('highScore', highScore);
    }
    
    // 显示通关画面
    document.getElementById('winScore').textContent = score;
    document.getElementById('winHighScore').textContent = highScore;
    document.getElementById('winKills').textContent = totalKills;
    document.getElementById('winCombo').textContent = maxCombo;
    document.getElementById('gameWinScreen').classList.remove('hidden');
}

// 事件监听
document.addEventListener('keydown', (e) => {
    keys[e.key] = true;
    
    if (e.key === ' ' && gameState === 'playing') {
        e.preventDefault();
        player.shoot();
    }
});

document.addEventListener('keyup', (e) => {
    keys[e.key] = false;
});

canvas.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect();
    mouseX = e.clientX - rect.left;
});

canvas.addEventListener('click', () => {
    if (gameState === 'playing') {
        player.shoot();
    }
});

canvas.addEventListener('mouseenter', () => {
    autoShoot = true;
});

canvas.addEventListener('mouseleave', () => {
    autoShoot = false;
});

// 触摸支持 - 优化移动端体验
let touchStartTime = 0;
let lastTouchX = null;

canvas.addEventListener('touchmove', (e) => {
    e.preventDefault();
    const rect = canvas.getBoundingClientRect();
    const touch = e.touches[0];
    
    // 计算相对于canvas的触摸位置
    const touchX = (touch.clientX - rect.left) * (canvas.width / rect.width);
    mouseX = touch.clientX - rect.left;
    lastTouchX = touchX;
    
    // 直接更新玩家位置以获得更快的响应
    if (gameState === 'playing' && player) {
        const targetX = touchX - player.width / 2;
        player.x = Math.max(0, Math.min(canvas.width - player.width, targetX));
    }
}, { passive: false });

canvas.addEventListener('touchstart', (e) => {
    e.preventDefault();
    touchStartTime = Date.now();
    
    const rect = canvas.getBoundingClientRect();
    const touch = e.touches[0];
    const touchX = (touch.clientX - rect.left) * (canvas.width / rect.width);
    mouseX = touch.clientX - rect.left;
    lastTouchX = touchX;
    
    if (gameState === 'playing') {
        autoShoot = true;
        player.shoot();
        
        // 立即更新玩家位置
        const targetX = touchX - player.width / 2;
        player.x = Math.max(0, Math.min(canvas.width - player.width, targetX));
    }
}, { passive: false });

canvas.addEventListener('touchend', (e) => {
    e.preventDefault();
    autoShoot = false;
    lastTouchX = null;
}, { passive: false });

// 防止页面滚动和缩放
document.body.addEventListener('touchmove', (e) => {
    if (e.target === canvas) {
        e.preventDefault();
    }
}, { passive: false });

// 防止双击缩放
let lastTouchEnd = 0;
document.addEventListener('touchend', (e) => {
    const now = Date.now();
    if (now - lastTouchEnd <= 300) {
        e.preventDefault();
    }
    lastTouchEnd = now;
}, { passive: false });

// 开始按钮
document.getElementById('startBtn').addEventListener('click', () => {
    document.getElementById('startScreen').classList.add('hidden');
    gameState = 'playing';
    initGame();
});

// 重新开始按钮
document.getElementById('restartBtn').addEventListener('click', () => {
    document.getElementById('gameOverScreen').classList.add('hidden');
    gameState = 'playing';
    initGame();
});

// 通关后重新开始按钮
document.getElementById('restartWinBtn').addEventListener('click', () => {
    document.getElementById('gameWinScreen').classList.add('hidden');
    gameState = 'playing';
    initGame();
});

// 初始化
initStars();
gameLoop();

